import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/views/home/view/leads/defeat_leads_reject_page.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';

import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../utils/size_utils.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/status_btn.dart';
import '../../../../widget/tab_btn.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_text.dart';
import '../../../../widget/w_toast.dart';
import '../../model/leads.dart';
import '../../model/leads_pool_model.dart';
import 'adviser_select_page.dart';
import 'leads_assign_detail_page.dart';

class DefeatAuditPage extends StatefulWidget {
  final String? phone;
  const DefeatAuditPage({super.key,this.phone});

  @override
  BaseState<DefeatAuditPage> createState() => _DefeatAuditPageState();
}

class _DefeatAuditPageState extends BaseState<DefeatAuditPage> {
  List<Map> statusList = [
    {"title": "全部", "value": null},
    {"title": "战败申请", "value": 10161005},
    {"title": "无效申请", "value": 10161006},
  ];

  List<Leads> dataList = [];

  bool isSelectedAll = false;
  Map sortParams = {};

  String autoPhone = "";

  WListViewState? listState;

  // int pageNum = 1;
  Map<String, dynamic> queryParams = {
    "current": 1,
    "size": 20,
  };

  @override
  void initState() {
    if (widget.phone != null) {
      queryParams["nameOrPhone"] = widget.phone;
      autoPhone = widget.phone!;
    }
    super.initState();
  }

  @override
  FullBasePage buildState(BuildContext context) {
    var paddingBottom = MediaQuery.of(context).padding.bottom;

    return FullBasePage(
        title: "战败审核",
        child: Column(
          children: [
            CustomSearch(
              hintText: "客户名称/手机号",
              initText: autoPhone,
              onSortClick: () {
                WPopupWindow.showSort(
                    context: context,
                    sortType: SortType.DEFEAT_AUDIT,
                    sortParams: sortParams,
                    isScrollControlled: true,
                    onSelected: (params) {
                      print("params$params");
                      sortParams = params;
                      params.forEach((key, value) {
                        queryParams[key] = value;
                        if (queryParams.containsKey(key) && value == null) {
                          queryParams.remove(key);
                        }
                      });
                      showLoading();
                      fetchDataList();
                    });
              },
              onTextChange: (text) {
                queryParams["current"] = 1;
                queryParams["nameOrPhone"] = text;
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            TabBtn(
              tabList: statusList,
              tabClick: (index) {
                queryParams["current"] = 1;
                queryParams["status"] = statusList[index]["value"];
                showLoading();
                fetchDataList();
              },
            ),
            Expanded(
                child: WListView(
              padding: EdgeInsets.zero,
              itemBuilder: _listItem,
              getDataList: (currentStatus, page) {
                listState = currentStatus;
                queryParams["current"] = page;
                fetchDataList();
              },
            )),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: () {
                    setState(() {
                      isSelectedAll = !isSelectedAll;
                      for (var item in dataList) {
                        item.isSelected = isSelectedAll;
                      }
                    });
                  },
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(
                            left: 25.px,
                            right: 10.px,
                            top: 16.px,
                            bottom: paddingBottom != 0 ? paddingBottom : 16.px),
                        child: isSelectedAll
                            ? Image.asset(
                                "images/ic_checked_circle.png",
                                color: WColors.primaryColor,
                                width: 25.px,
                              )
                            : Image.asset(
                                "images/ic_check_circle.png",
                                color: WColors.primaryColor,
                                width: 25.px,
                              ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(
                            top: 16.px,
                            bottom: paddingBottom != 0 ? paddingBottom : 16.px),
                        child: WText(
                          "全选",
                          style: TextStyle(
                              fontSize: WDimens.tsMedium,
                              color: WColors.mainTextColor),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(
                      left: 15.px,
                      right: 15.px,
                      top: 16.px,
                      bottom: paddingBottom != 0 ? paddingBottom : 16.px),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      StatusBtn(
                        isItemBtn: true,
                        text: "再分配",
                        color: WColors.orange,
                        height: 32.px,
                        width: 80.px,
                        isTag: true,
                        fontSize: WDimens.tsMedium,
                        onPressed: () {
                          if (dataList
                              .every((item) => item.isSelected == false)) {
                            Toast.toast("请先选择线索");
                            return;
                          }
                          List<int> clueIds = [];
                          for (int i = 0; i < dataList.length; i++) {
                            if (dataList[i].isSelected == true) {
                              clueIds.add(dataList[i].id!);
                            }
                          }
                          showLoading();
                          Map params = {"idList": clueIds, "entrance": 2};
                          HttpUtils()
                              .post(Api.checkClueStatus, data: params)
                              .then((value) {
                            hideLoading();
                            if (value.resultCode == 200) {
                              RouteHelper.pushWidget(
                                  context,
                                  AdviserSelectPage(
                                    type: OperateType.allocationClue,
                                    clueIds: clueIds,
                                    entrance: 2,
                                  )).then((isSuccess) {
                                queryParams["current"] = 1;
                                fetchDataList();
                              });
                            } else {
                              Toast.toast(value.errMsg);
                            }
                          });
                        },
                      ),
                      StatusBtn(
                        isItemBtn: true,
                        text: "确认",
                        color: WColors.primaryColor,
                        height: 32.px,
                        width: 60.px,
                        isTag: true,
                        margin: EdgeInsets.only(left: 10.px),
                        fontSize: WDimens.tsMedium,
                        onPressed: () {
                          if (dataList
                              .every((item) => item.isSelected == false)) {
                            Toast.toast("请先选择线索");
                            return;
                          }
                          showLoading();
                          Map params = {"idList": getClueIds(), "entrance": 2};
                          HttpUtils()
                              .post(Api.checkClueStatus, data: params)
                              .then((value) {
                            hideLoading();
                            if (value.resultCode == 200) {
                              CommonUtils.throttle(defeatPass);
                            } else {
                              Toast.toast(value.errMsg);
                            }
                          });
                        },
                      ),
                      StatusBtn(
                        isItemBtn: true,
                        text: "驳回",
                        color: WColors.redMain,
                        height: 32.px,
                        width: 60.px,
                        isTag: true,
                        margin: EdgeInsets.only(left: 10.px),
                        fontSize: WDimens.tsMedium,
                        onPressed: () {
                          if (dataList
                              .every((item) => item.isSelected == false)) {
                            Toast.toast("请先选择线索");
                            return;
                          }
                          showLoading();
                          Map params = {"idList": getClueIds(), "entrance": 2};
                          HttpUtils()
                              .post(Api.checkClueStatus, data: params)
                              .then((value) {
                            hideLoading();
                            if (value.resultCode == 200) {
                              RouteHelper.pushWidget(
                                  context,
                                  DefeatLeadsRejectPage(
                                    clueIds: getClueIds(),
                                  )).then((isSuccess) {
                                queryParams["current"] = 1;
                                fetchDataList();
                              });
                            } else {
                              Toast.toast(value.errMsg);
                            }
                          });
                        },
                      )
                    ],
                  ),
                )
              ],
            ),
          ],
        ));
  }

  List<int> getClueIds() {
    List<int> clueIds = [];
    for (int i = 0; i < dataList.length; i++) {
      if (dataList[i].isSelected == true) {
        clueIds.add(dataList[i].id!);
      }
    }
    return clueIds;
  }

  defeatPass() {
    Map params = {"clueIdList": getClueIds(), "result": true, "noPassReason": null};
    showLoading();
    HttpUtils().post(Api.examineOperator, data: params).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        Toast.toast("审核成功");
        queryParams["current"] = 1;
        fetchDataList();
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }

  void fetchDataList() {
    HttpUtils().post(Api.getDefeatExamineList, data: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          setState(() {
            statusList = [
              {"title": "全部", "value": null},
              {"title": "战败申请 ${value.data["loseApplyNum"]}", "value": 10161005},
              {"title": "无效申请 ${value.data["invalidApplyNum"]}", "value": 10161006},
            ];
          });

          List data = value.data["records"] ?? [];
          List<Leads> list = data.map((item) => Leads.fromJson(item)).toList();
          listState?.onRefreshData(list, queryParams["current"]);
          if (queryParams["current"] == 1) {
            dataList.clear();
          }
          dataList.addAll(list);
          isSelectedAll = false;
          setState(() {});
        }
      } else {
        listState?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
      listState?.onFail(e);
    });
  }

  Widget _listItem(context, index, dataList) {
    Leads item = dataList[index];

    String sexStr= CommonReqUtils.exchangeCodeToName(CommonReqUtils.sex, item.sex);
    if (sexStr.isNotEmpty) {
      sexStr = " • $sexStr";
    }

    return GestureDetector(
        onTap: () => {
              RouteHelper.pushWidget(
                  context,
                  LeadsAssignDetailPage(
                    clueId: item.id!,
                  )).then((isSuccess) {
                queryParams["current"] = 1;
                fetchDataList();
              })
            },
        child: Container(
          decoration: BoxDecoration(boxShadow: [
            BoxShadow(
                color: WColors.CDFEFFB,
                offset: const Offset(0, 1),
                blurRadius: 3.px)
          ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
          margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
          padding: EdgeInsets.only(top: 10.px, bottom: 10.px, right: 10.px),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    marginRight: 10.px,
                    color: WColors.primaryColor,
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        item.isSelected = !item.isSelected;
                        isSelectedAll =
                            !dataList.any((item) => item.isSelected == false);
                      });
                    },
                    child: Padding(
                      padding: EdgeInsets.only(
                        right: 10.px,
                      ),
                      child: item.isSelected
                          ? Image.asset(
                              "images/ic_checked_circle.png",
                              color: WColors.primaryColor,
                              width: 18.px,
                            )
                          : Image.asset(
                              "images/ic_check_circle.png",
                              color: WColors.primaryColor,
                              width: 18.px,
                            ),
                    ),
                  ),
                  Flexible(
                    flex: 1,
                    child: WText(
                      item.customerName ?? "",
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.mainTextColor,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                  Flexible(
                    flex: 2,
                    child: WText(
                      sexStr,
                      style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.subTextColor),
                    ),
                  ),
                ],
              ),
              WLine(
                marginTop: 6.px,
                height: 0.5.px,
                marginBottom: 10.px,
                marginLeft: 10.px,
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.px),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        StatusBtn(
                          height: 24.px,
                          text: CommonReqUtils.exchangeCodeToName(
                              CommonReqUtils.leadsStatus, item.status),
                          color: CommonReqUtils.exchangeCodeToName(
                                      CommonReqUtils.followUpResult,
                                      item.defeatInvalidResult) ==
                                  "战败申请"
                              ? WColors.redMain
                              : WColors.hintTextColor,
                          isTag: true,
                          isItemBtn: true,
                        ),
                        SizedBox(
                          width: 10.px,
                        ),
                        StatusBtn(
                          height: 24.px,
                          width: 32.px,
                          isItemBtn: true,
                          text: CommonReqUtils.exchangeCodeToName(
                              CommonReqUtils.intentRange, item.level),
                          color: WColors.border,
                          fontColor: WColors.primaryColor,
                          //  color: priorityStyle["color"],
                        ),
                        SizedBox(
                          width: 10.px,
                        ),
                        StatusBtn(
                          height: 24.px,
                          text: "跟进次数: ${item.followTimes}",
                          color: WColors.orange,
                          isItemBtn: true,
                        ),
                        SizedBox(
                          width: 10.px,
                        ),
                        StatusBtn(
                          height: 24.px,
                          text: CommonReqUtils.exchangeCodeToName(
                              CommonReqUtils.leaderSource, item.clueSource),
                          isItemBtn: true,
                          //   color: sourceStyle["color"],
                          color: WColors.border,
                          fontColor: WColors.mainTextColor,
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      item.phone ?? "",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    Row(
                      children: [
                        WText(
                          item.modelName ?? "",
                          style: TextStyle(
                              fontSize: WDimens.tsMedium,
                              color: WColors.mainTextColor),
                        ),
                        SizedBox(
                          width: 20.px,
                        ),
                        WText(
                          item.salemanName ?? "",
                          style: TextStyle(
                              fontSize: WDimens.tsMedium,
                              color: WColors.mainTextColor),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    if (CommonReqUtils.exchangeCodeToName(
                            CommonReqUtils.followUpResult,
                            item.defeatInvalidResult) ==
                        "战败")
                      WText(
                        "战败原因: ${CommonReqUtils.exchangeCodeToName(CommonReqUtils.defeatResult, item.defeatInvalidReason)}",
                        style: TextStyle(
                            fontSize: WDimens.tsMedium,
                            color: WColors.mainTextColor),
                      ),
                    if (CommonReqUtils.exchangeCodeToName(
                            CommonReqUtils.followUpResult,
                            item.defeatInvalidResult) ==
                        "无效")
                      WText(
                        "无效原因: ${CommonReqUtils.exchangeCodeToName(CommonReqUtils.invalidityReason, item.defeatInvalidReason)}",
                        style: TextStyle(
                            fontSize: WDimens.tsMedium,
                            color: WColors.mainTextColor),
                      ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      "线索创建: ${item.createdAt}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.hintTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      "申请时间: ${item.defeatInvalidTime}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.hintTextColor),
                    ),
                  ],
                ),
              )
            ],
          ),
        ));
  }
}
